<template>
  <app-page card full>
    <template #header>{{ moduleDetail.moduleName }}</template>

    <el-form
      ref="formRef"
      :model="moduleDetail.moduleData"
      label-width="110px"
      label-position="left"
      @submit.prevent="handleSubmit"
    >
      <ModelData :module-detail="moduleDetail" v-if="moduleDetail.moduleType == 0" />
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
      <el-button type="default" @click="$router.go(-1)">返回</el-button>
    </template>
  </app-page>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { http } from 'jax-node'
import { useRoute } from 'vue-router'
import ModelData from './component/ModelData.vue'

const route = useRoute()

const moduleId = route.query.moduleId
const formRef = ref()
const moduleDetail = ref({})

const handleSubmit = () => {
  http
    .put(
      `/module/${moduleId}`,
      {
        moduleData: moduleDetail.value.moduleData,
      },
      {
        showLoading: '保存中...',
      }
    )
    .then(res => {
      ElMessage.success('保存成功')
    })
}

const initData = () => {
  http({
    url: `/module/${moduleId}`,
  }).then(res => {
    const data = {
      moduleData: {},
      ...res,
    }

    // 初始化moduleData
    data.model.modelSchema.map(modelItem => {
      const name = modelItem.name || modelItem.label
      const dataType = modelItem.dataType

      if (dataType == 'ObjectData') {
        if (data.moduleData[name] == undefined) data.moduleData[name] = {}
      } else if (dataType == 'ArrayData') {
        if (data.moduleData[name] == undefined) data.moduleData[name] = []
      }
    })

    moduleDetail.value = data
  })
}

initData()
</script>

<style lang="scss" scoped></style>
